/*
* Copyright (c) 2010-2013 Ruben Chakhmakhchyan. All rights reserved.
* 
* This file contains Original Code and/or Modifications of Original Code
* as defined in and that are subject to the Eclipse Public License
* Version 1.0 (the 'License'). You may not use this file except in
* compliance with the License. Please obtain a copy of the License at
* http://opensource.org/licenses/EPL-1.0 and read it before using this file.
*/

#include "wiacommon.h"
#include "event_callback.h"

//#define _TEST


CEventCallback::CEventCallback( MessageListener* messageListener )
{
    m_cRef = 0;
    m_messageListener = messageListener;
}

STDMETHODIMP CEventCallback::QueryInterface( REFIID iid, LPVOID *ppvObj )
{
    if ( ppvObj == NULL )
    {
        return E_POINTER;
    }

    if ( iid == IID_IUnknown )
    {
        *ppvObj = ( IUnknown* ) this;
    }
    else if ( iid == IID_IWiaEventCallback )
    {
        *ppvObj = ( IWiaEventCallback* ) this;
    }
    else
    {
        *ppvObj = NULL;
        return E_NOINTERFACE;
    }

    AddRef();

    return S_OK;
}

STDMETHODIMP_(ULONG) CEventCallback::AddRef()
{
    return ::InterlockedIncrement( &m_cRef );
}

STDMETHODIMP_(ULONG) CEventCallback::Release()
{
    LONG cRef = ::InterlockedDecrement( &m_cRef );

    if ( cRef == 0 )
        delete this;

    return cRef;
}

STDMETHODIMP CEventCallback::ImageEventCallback( LPCGUID pEventGuid, BSTR bstrEventDescription, BSTR bstrDeviceID, BSTR bstrDeviceDescription, DWORD dwDeviceType, BSTR bstrFullItemName, ULONG *pulEventType, ULONG ulReserved )
{
    if ( !::memcmp( pEventGuid, &WIA_EVENT_DEVICE_CONNECTED, sizeof( WIA_EVENT_DEVICE_CONNECTED ) ) )
    {
#ifdef _TEST
        ::printf( "CONNECTED\n" );
#endif
        m_messageListener->onDeviceConnection( true );
    }
    else if ( !::memcmp( pEventGuid, &WIA_EVENT_DEVICE_DISCONNECTED, sizeof( WIA_EVENT_DEVICE_DISCONNECTED ) ) )
    {
#ifdef _TEST
        ::printf( "DISCONNECTED\n" );
#endif
        m_messageListener->onDeviceConnection( false );
    }
    return S_OK;
}

